package com.yixin.vuehr.web.controller.upload;

import com.yixin.vuehr.bean.RespBean;
import com.yixin.vuehr.service.HrService;
import com.yixin.vuehr.web.util.FastDFSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
public class UploadController {
    SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
    @Autowired
    HrService hrService;

    @Value("${fastdfs.nginx.host}")
    String nginxHost;
    //上传用户头像
    @PostMapping("/userface")
    public RespBean upLoadUserFace(MultipartFile file){
        String fileId = FastDFSUtils.upload(file);
        String token = FastDFSUtils.getToken(fileId.substring(fileId.indexOf('/')+1));
        String url = nginxHost + fileId+token;
        if (hrService.updateHrUserFace(url)==1){
            return RespBean.ok("头像上传成功").setObj(url);
        }
        return RespBean.error("头像上传失败");
    }

//    @PostMapping("/userface")
//    public RespBean upLoadUserFace(MultipartFile file, HttpServletRequest req){
//        String format = sdf.format(new Date());
//        String realPath = req.getServletContext().getRealPath("/img") + format;
//        File folder = new File(realPath);
//        boolean can = false;
//        if (!folder.exists()){
//            can = folder.mkdirs();
//        }
//        String oldName = file.getOriginalFilename();
//        String newName = UUID.randomUUID().toString()+oldName.substring(oldName.lastIndexOf("."));
//        try {
//            file.transferTo(new File(folder,newName));
//            String url = req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+"/img"+format+newName;
//            hrService.updateHrUserFace(url);
//            return RespBean.ok("头像上传成功").setObj(url);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return RespBean.error("头像上传失败");
//    }
}
